package org.example.flea_market_mvc.controller;

import org.example.flea_market_mvc.entity.Orders;
import org.example.flea_market_mvc.param.OrderParam;
import org.example.flea_market_mvc.service.orders.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/orders")
@Validated
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @PostMapping
    public ApiResponse<String> createOrder(@Valid @RequestBody OrderParam orderParam) {
        int result = ordersService.insert(orderParam);
        return result > 0 ? ApiResponse.success("创建订单成功") : ApiResponse.error(400, "创建订单失败");
    }

    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteOrder(@PathVariable Long id) {
        int result = ordersService.deleteById(id);
        return result > 0 ? ApiResponse.success("删除订单成功") : ApiResponse.notFound("订单不存在");
    }


    @PutMapping
    public ApiResponse<String> updateOrder(@Valid @RequestBody OrderParam orderParam) {
        int result = ordersService.update(orderParam);
        return result > 0 ? ApiResponse.success("更新订单成功") : ApiResponse.notFound("订单不存在");
    }

    @GetMapping("/{id}")
    public ApiResponse<Orders> getOrder(@PathVariable Long id) {
        Orders order = ordersService.selectById(id);
        return order != null ? ApiResponse.success(order) : ApiResponse.notFound("订单不存在");
    }
    @GetMapping("/selectByUser/{id}")
    public ApiResponse<List<Orders>> getOrderByUserId(@PathVariable Long id){
        List<Orders> orders =  ordersService.selectByUserId(id);
        return ApiResponse.success(orders);
    }

    @GetMapping
    public ApiResponse<List<Orders>> getAllOrders() {
        List<Orders> orders = ordersService.selectAll();
        return ApiResponse.success(orders);
    }

    /**
     * 购物车结算生成订单
     * @param userId 用户ID
     * @param cartItemIds 购物车项ID列表
     */
    @PostMapping("/checkout")
    public ApiResponse<String> checkout(@RequestParam Integer userId, @RequestBody List<Integer> cartItemIds) {
        boolean success = ordersService.checkout(userId, cartItemIds);
        return success ? ApiResponse.success("结算成功，订单已生成") : ApiResponse.error(400, "结算失败");
    }
}